import struct
from base64 import b64encode
from base64 import b64decode
from local_log import logger
from enc import RsaEncryption

# 认证响应
MSG_AUTH_RESULT = 0
# 数据传输
MSG_DATA = 1
# 心跳
MSG_KEEPLIVE = 2

g_enc = RsaEncryption()
g_dec = RsaEncryption()
g_key = 'dsklfskldskfsdff'
g_enc.aes_set_key(g_key.encode())
g_dec.aes_set_key(g_key.encode())

class CommMsg():
    def __init__(
            self,
            cmd: int = 0,
            uuid: bytes = bytes(),
            data: bytes = bytes()):
        self.cmd = cmd
        self.uuid = uuid
        self.hd_len = 36
        self.data = data

    def pack(self):
        try:
            # bs_data = b64encode(self.data)
            # bs_data = g_enc.aes_encrypt(self.data)
            bs_data = self.data
            if not bs_data:
                return None
            return struct.pack(
                '>I32s%ds' %
                (len(bs_data)),
                self.cmd,
                self.uuid,
                bs_data)
        except Exception as e:
            logger.debug(f'msg pack err {self} {e}')
            return None

    def unpack(self, data):
        try:
            if len(data) < self.hd_len:
                logger.debug(f'data len is too short {len(data)}')
                return False
            self.cmd, self.uuid, bs_data = struct.unpack(
                '>I32s%ds' %
                (len(data) - self.hd_len), data)
            # self.data = b64decode(bs_data)
            # self.data = g_dec.aes_decryypt(bs_data)
            self.data = bs_data
            if not self.data:
                return False
            return True
        except Exception as e:
            logger.debug(f'msg unpack err {self} {e}')
            return False


def dump_hex(desc, data):
    logger.debug(f'{desc}:\n')
    tstr = ''
    index = 0
    for it in data:
        index = index + 1
        tstr += '%02x ' % it
        if index % 16 == 0:
            tstr += '\n'
    tstr += '\n'
    logger.debug(tstr)
